<template>
  <v-form v-model="valid" ref="brandform">
    <v-text-field v-model="brand.name" label="请输入品牌名称" required
                :rules="[v => !!v || '品牌名称不能为空'
                ]"
    />
    <v-text-field v-model="brand.letter" label="请输入品牌首字母" required
                 mask="A" :rules="[v => !!v || '品牌首字母不能为空'
                ]"
    />
    <v-cascader
      url="/item/category/list"
      multiple
      required
      v-model="brand.categories"
      label="请选择商品分类"/>
    <v-layout row>
      <v-flex xs3>
        <span style="font-size: 16px; color: #444">品牌LOGO：</span>
      </v-flex>
      <v-flex>
        <v-upload
          v-model="brand.image"
          url="/upload/image"
          :multiple="false"
          :pic-width="250"
          :pic-height="90"
        />
      </v-flex>
    </v-layout>
    <v-layout row class="pt-5" >
      <v-spacer/>
      <v-btn @click="submit" color="primary">提交</v-btn>
      <v-btn @click="clear" color="warning" >重置</v-btn>
    </v-layout>
  </v-form>
</template>

<script>
    export default {
        name: "MyBrandForm",
      //在data中定义一个valid属性，跟表单的value进行双向绑定，观察表单是否通过校验，
      // 同时把等会要跟表单关联的品牌brand对象声明出来：
      data(){
        return{
          valid:false,// 表单校验结果标记
          brand:{
            name:"",// 品牌名称
            letter:"",// 品牌首字母
            image:"",// 品牌logo
            categories:[], // 品牌所属的商品分类数组
          }
        }

      },
      methods:{
        submit(){
          //{name: "woji", letter: "W", image: "", categories: [{name: "燃气灶", id: 120}]}
          // categories: [{name: "燃气灶", id: 120}]
          //0: {name: "燃气灶", id: 120}
          //image: ""
          //letter: "W"
          //name: "woji"

          //新增品牌，品牌信息+商品分类的最后级分类名称和id   ===> {name: "woji", letter: "W", image: "", categories: [{name: "燃气灶", id: 120}]}
          if(this.$refs.brandform.validate()){
            //解构表达式获取品牌中数据，除了categories以外的都存储到rest中
            const {categories,...rest} = this.brand;
            //对categories进行处理，得到里面的id，赋值给rest中categories
            rest.categories = categories.map(c =>c.id).join(",");
            this.$http.post("/item/brand",this.$qs.stringify(rest))
              .then(resp=>{
                // 关闭窗口
                this.$message.success("保存成功！");
                this.closeWindow();
              })
              .catch(()=>{
                this.$message.error("保存失败！");
              })
          }
        }
      }

    }
</script>

<style scoped>

</style>
